package zzr.library.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

import zzr.library.databinding.LayoutBorrowItemBinding;
import zzr.library.db.obj.combine.BorrowWithBook;

public class BorrowItemAdapter extends RecyclerView.Adapter<BorrowItemAdapter.BorrowItemViewHolder> {

    private List<BorrowWithBook> borrows;

    public BorrowItemAdapter(List<BorrowWithBook> borrows) {
        this.borrows = borrows;
    }

    @NonNull
    @Override
    public BorrowItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutBorrowItemBinding inflate = LayoutBorrowItemBinding.inflate(LayoutInflater.from(parent.getContext()));
        inflate.getRoot().setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        return new BorrowItemViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull BorrowItemViewHolder holder, int position) {
        holder.setData(borrows.get(position));
    }

    @Override
    public int getItemCount() {
        return borrows.size();
    }

    public static class BorrowItemViewHolder extends RecyclerView.ViewHolder {
        public LayoutBorrowItemBinding layoutBorrowItemBinding;

        public BorrowItemViewHolder(LayoutBorrowItemBinding layoutBorrowItemBinding) {
            super(layoutBorrowItemBinding.getRoot());
            this.layoutBorrowItemBinding = layoutBorrowItemBinding;
        }

        public void setData(BorrowWithBook borrow) {
            layoutBorrowItemBinding.itemBid.setText(borrow.book.bid+"");
            layoutBorrowItemBinding.itemBookName.setText(borrow.book.name);
            layoutBorrowItemBinding.itemIsbn.setText(borrow.book.isbn);
            String status;
            boolean returned = borrow.borrow.returned;
            if (returned) {
                status = "已经归还";
            } else {
                LocalDateTime dueTime = borrow.borrow.dueTime;
                LocalDateTime now = LocalDateTime.now();
                if (now.isAfter(dueTime)) {
                    status = "超期" + Duration.between(dueTime, now).toDays() + "天";
                } else {
                    status = "还有" + Duration.between(now, dueTime).toDays() + "天需归还";
                }
            }
            layoutBorrowItemBinding.itemStatus.setText(status);

        }

    }


}
